
package inf3791.calendarsystem.others.panels.patients;

import eu.mpower.framework.management.patientmanagement.soap.GetPatientsForUserMessage;
import eu.mpower.framework.management.patientmanagement.soap.Patient;
import eu.mpower.framework.management.patientmanagement.soap.PatientsResponseMessage;
import eu.mpower.framework.security.types.soap.SecurityToken;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author Jonas Weber
 */
class PatientTableModel extends AbstractTableModel {

    List<Patient> patients = null;

    /**
     * Forces a refresh of the cached list from the server.
     *
     * Preferably called in a background thread.
     */
    public synchronized void forceRefresh(SecurityToken securitytoken) {
        GetPatientsForUserMessage msg = new GetPatientsForUserMessage();
        msg.setSecurityToken(securitytoken);
        msg.setUserID(securitytoken.getUserID());

        PatientsResponseMessage prm = getPatientsForUser(msg);

        if (prm.getStatus().getResult() == 0) {
            patients = prm.getPatients();
            Logger.getLogger(this.getClass().getName()).log(Level.INFO, "List of patients succeed: {0}", prm.getPatients().size());

        } else {
            Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "List of patients failed: {0}", prm.getStatus().getErrorCause());
        }

        fireTableDataChanged();
    }

    private static PatientsResponseMessage getPatientsForUser(eu.mpower.framework.management.patientmanagement.soap.GetPatientsForUserMessage userIDmsg) {
        eu.mpower.framework.management.patientmanagement.soap.PatientManagement service = new eu.mpower.framework.management.patientmanagement.soap.PatientManagement();
        eu.mpower.framework.management.patientmanagement.soap.IPatientManagement port = service.getIPatientManagement();
        return port.getPatientsForUser(userIDmsg);
    }

    @Override
    public synchronized int getRowCount() {
        if (patients == null) {
            return 0;
        } else {
            return patients.size();
        }
    }

    @Override
    public int getColumnCount() {
        return 1;
    }

    @Override
    public Object getValueAt(int row, int col) {

        return patients.get(row);

    }
    
    public void empty()
    {
        if (patients != null) {
            patients.clear();
        }
        fireTableDataChanged();
    }
}
